#include "CaptureThread.h"

CaptureThread::CaptureThread(QObject *parent) : QThread(parent) {
    //cam = camera;
    running_flag = false;
    is_connected = false;
}

void CaptureThread::run() {
    double a=0;
    QTime delay;
    Mat img;

    running_flag = is_connected;
    while(1) {
        istheEnd.lock();
        if(!running_flag){
            cout << "Stopped CaptureThread" << endl;
            istheEnd.unlock();
            break;
        }
        istheEnd.unlock();
        frame.dtime = delay.elapsed();
        delay.restart();
        cam >> img;

        img.copyTo(frame.image);
        frames.push_back(frame);
        frame.image.release();

        //imshow("webcam",img);
        //waitKey(1);

        cout << "frame No: " << a++ << " -> delta_time: " << frame.dtime << " ms" << endl;
        //msleep(100);
    }
}

void CaptureThread::stop() {
    istheEnd.lock();
    running_flag = false;
    istheEnd.unlock();
}

bool CaptureThread::connect_localcamera(int dev)
{
    is_connected = cam.open(dev);
    return is_connected;
}

bool CaptureThread::connect_ipcamera(QString ip, QString showable)
{
    cout << "Connecting to: " << showable.toStdString() << endl;
    is_connected = cam.open(ip.toStdString());
    return is_connected;
}

bool CaptureThread::open_video(QString dir)
{
    return false; // still not working
}

Frame CaptureThread::getFrameAt(int i)
{
    Frame temp;

    if(i>=0 && (unsigned)i<frames.size()) {
        temp.dtime = frames[i].dtime;
        frames[i].image.copyTo(temp.image);
    }

    return temp;
}

bool CaptureThread::frameExists(int i)
{
    return (frames.size()>i && i>=0)? true : false;
}

int CaptureThread::getNoFrames()
{
    return frames.size();
}

void CaptureThread::save_vector() {
    int no_frames = frames.size();
    if(no_frames==0)
        return;

    for(int i=0; i<no_frames;i++)
    {
        imwrite(QString("./video/frame"+QString::number(i)+"-"+QString::number(frames[i].dtime)+".jpg").toStdString(),frames[i].image);
    }

    emit update_status("sector saving succeded");
}

